package org.galaxyworld.flycode.core;

import org.apache.commons.io.FilenameUtils;
import org.beetl.core.*;
import org.beetl.core.resource.FileResourceLoader;
import org.galaxyworld.flycode.model.Field;
import org.galaxyworld.flycode.model.Table;
import org.galaxyworld.flycode.utils.FieldVirtualAttribute;
import org.galaxyworld.flycode.utils.TableVirtualAttribute;

import java.io.IOException;
import java.util.Map;

public class TemplateManager {

    private static GroupTemplate groupTemplate;

    static {
        String root = FilenameUtils.separatorsToSystem(String.format("%s/templates", System.getProperty("user.dir")));
        FileResourceLoader resourceLoader = new FileResourceLoader(root, "utf-8");
        try {
            Configuration cfg = Configuration.defaultConfiguration();
            groupTemplate = new GroupTemplate(resourceLoader, cfg);

            groupTemplate.registerVirtualAttributeClass(Field.class, new FieldVirtualAttribute());
            groupTemplate.registerVirtualAttributeClass(Table.class, new TableVirtualAttribute());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void addSharedVariables(Map<String, Object> sharedVariables) {
        if (groupTemplate.getSharedVars() != null) {
            sharedVariables.putAll(groupTemplate.getSharedVars());
        }
        groupTemplate.setSharedVars(sharedVariables);
    }

    public static Template getTemplate(String name) {
        return groupTemplate.getTemplate(name);
    }

}
